<template>
  <div class="header-container">
    <nav-bar
      :title="'账号管理'"
      :showLeftArrow="true"
      :leftText="'返回'"
      @click-left="back"
    >
    </nav-bar>
  </div>
  <div class="main-container">
    <van-form @submit.prevent>
      <van-cell-group inset>
        <van-field name="uploader" label="头像">
          <template #input>
            <van-uploader
              v-model="fileList"
              upload-text="上传"
              :after-read="afterRead"
              :max-count="1"
              @delete="removeAvatar"
            />
          </template>
        </van-field>
        <van-field
          v-model="current.username"
          disabled
          name="用户名"
          label="用户名"
          placeholder="用户名"
        />
        <van-field
          v-model="current.nickname"
          name="昵称"
          label="昵称"
          placeholder="昵称"
        />
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" @click="save"> 保存 </van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block @click="changePassword"> 修改密码 </van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block @click="logout"> 退出登录 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import { useRouter } from "vue-router";
import UmsMember from "@/entity/UmsMember";
import authService from "@/services/auth.service";
import { AxiosError } from "axios";
import { Toast, UploaderFileListItem } from "vant";
import memberService from "@/services/member.service";
import fileService from "@/services/file.service";
import { useStore } from "vuex";
import { UN_AUTHENTICATE } from "@/store";

type StateType = {
  current: UmsMember;
  fileList: UploaderFileListItem[];
};
export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const state = reactive<StateType>({
      current: new UmsMember(),
      fileList: [],
    });

    onMounted(async () => {
      load();
    });

    const load = async () => {
      try {
        const current = await authService.current();
        state.current = current;
        if (state.current.avatarUrl != null) {
          state.fileList = [
            {
              url: state.current.avatarUrl,
            },
          ];
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const back = () => {
      router.back();
    };

    const save = async () => {
      try {
        let id = await memberService.update(state.current);
        Toast.success("保存成功");
        load();
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("保存失败");
        throw e;
      } finally {
      }
    };

    const changePassword = () => {
      router.push("/change-password");
    };

    const logout = async () => {
      try {
        await authService.logout();
        store.commit(UN_AUTHENTICATE);
        router.push("/");
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("注销失败");
        throw e;
      } finally {
      }
    };

    const afterRead = async (fileListItem: UploaderFileListItem) => {
      try {
        if (fileListItem.file == null) {
          return;
        }

        fileListItem.status = "uploading";
        fileListItem.message = "上传中...";
        const url = await fileService.upload(fileListItem.file);
        state.current.avatarUrl = url;
        fileListItem.status = "done";
        fileListItem.message = "上传成功";
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        fileListItem.status = "failed";
        fileListItem.message = "上传失败";
        throw e;
      } finally {
      }
    };

    const removeAvatar = (fileListItem: UploaderFileListItem) => {
      state.current.avatarUrl = null;
    };

    return {
      ...toRefs(state),
      back,
      save,
      changePassword,
      logout,
      afterRead,
      removeAvatar,
    };
  },
});
</script>

<style scoped></style>
